package com.hanserwei.han_picture.manager;

import com.hanserwei.han_picture.config.TencentCosClient;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * 通用的文件上传与下载
 */
@Component
@RequiredArgsConstructor
public class CosManager {
    /**
     * 腾讯云 COS 配置
     */
    private final TencentCosClient tencentCosClient;

    /**
     * 腾讯云 COS 客户端
     */
    private final COSClient cosClient;


    /**
     * 上传本地文件到 COS
     *
     * @param key  对象键, 域名后面的部分
     * @param file 本地文件
     * @return COS 客户端
     */
    public PutObjectResult putObject(String key, File file) {
        String bucketName = tencentCosClient.getBucket();
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
        // 设置存储类型, 默认标准存储(Standard), 可选低频访问存储(Standard_IA)
        putObjectRequest.setStorageClass(StorageClass.Standard);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 获取 COS 文件对象
     *
     * @param key 对象键, 域名后面的部分
     * @return COS 对象
     */
    public COSObject getObject(String key) {
        String bucketName = tencentCosClient.getBucket();
        return cosClient.getObject(bucketName, key);
    }

    /**
     * 上传图片到 COS, 并使用数据万象解析图片信息
     *
     * @param key  对象键, 域名后面的部分
     * @param file 图片文件
     * @return COS 客户端
     */
    public PutObjectResult putPictureObject(String key, File file) {
        String bucketName = tencentCosClient.getBucket();
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, file);
        // 对图片进行处理（获取基本信息也是处理！）
        PicOperations picOperations = new PicOperations();
        // 设置是否返回图片的信息，1：返回，0：不返回
        picOperations.setIsPicInfo(1);
        // 设置数据万象处理参数
        putObjectRequest.setPicOperations(picOperations);
        return cosClient.putObject(putObjectRequest);
    }
}